package com.xhui.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhui.reggie.common.R;
import com.xhui.reggie.entity.Category;
import com.xhui.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;


/**
 * 处理菜品菜系、菜品套餐的相关操作
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Resource
    private CategoryService categoryService;

    /**
     * 新增菜系、套餐
     * @param category 前端菜品信息
     * @return 实体R<String>
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info(" category ==> {}", category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 获取分类信息
     * @param page 页数
     * @param pageSize 每页展示条数
     * @return 所有菜品分类信息
     */
    @GetMapping("/page")
    public R<Page<Category>> getPage(int page, int pageSize){
        // 1. 封装页面信息
        Page<Category> categoryPage = new Page<>(page, pageSize);
        // 2. 将查询条件进行封装
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        // 根据更新时间进行降序
        queryWrapper.orderByAsc(Category::getSort);
        Page<Category> page1 = categoryService.page(categoryPage, queryWrapper);
        return R.success(categoryPage);
    }

    /**
     * 删除菜系/套餐，若有一个被引用，则无法进行删除
     * @param ids 待删除的ids
     * @return 实体R
     */
    @DeleteMapping
    public R<String> delete(Long ids){
        categoryService.remove(ids);
        return R.success("分类信息删除成功");
    }

    /**
     * 更新分类
     * @param category 更新那个菜品
     * @return 实体R
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }

    /**
     * 查询分类信息
     * @param category 分类封装对象
     * @return 分类信息
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort);
        categoryLambdaQueryWrapper.orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(categoryLambdaQueryWrapper);
        return R.success(list);
    }
}
